##########################################################################################

library(data.table)
library(optparse)
library(Seurat)
library(ArchR)

##########################################################################################
option_list <- list(
    make_option(c("--comine_data_file"), type = "character"),
    make_option(c("--scriptPath"), type = "character"),
    make_option(c("--out_path"), type = "character") 
)

if(1!=1){
    
    ## 整合atac和rna的文件
    comine_data_file <- "~/20231121_singleMuti/results/subcell/cluster5/cluster5.combineRNA.motif_peak2gene.Rdata"

    ## 既往研究整理的代码
    scriptPath <- "~/20231121_singleMuti/scripts/scScalpChromatin"

    ## 输出
    out_path <- "~/20231121_singleMuti/results/celltype_plot/peakMA"

}

###########################################################################################
parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

comine_data_file <- opt$comine_data_file
scriptPath <- opt$scriptPath
out_path <- opt$out_path

dir.create(out_path , recursive = T)

###########################################################################################
## 导入数据
a <- load(comine_data_file)
## atac_proj

## 细胞类型
use_groups <- unique(atac_proj@cellColData$Sample)
cellType <- unique(atac_proj@cellColData$cell_type)

###########################################################################################
## 简单差异的peak
markerPeaks <- getMarkerFeatures(
    ArchRProj = atac_proj, 
    useMatrix = "PeakMatrix", 
    groupBy = "Sample",
    useGroups = use_groups,
    bias = c("TSSEnrichment", "log10(nFrags)"),
    testMethod = "wilcoxon"
)

for( sample in colnames(markerPeaks) ){
  pma <- markerPlot(seMarker = markerPeaks, name = sample , cutOff = "FDR <= 0.1 & Log2FC >= 0.5", plotAs = "MA")
  out_file <- paste0( out_path , "/" , cellType , "_" , sample , "_DiffPeakBetweenSample.pdf" ) 
  pdf(out_file , height = 10 , width = 7)
  print(pma)
  dev.off()
}